package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishService dishService;


    @Override
    public void save(DishDTO dishDTO) {

        // 1.新增菜品，不包含口味
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.save(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        // 2.新增口味表到dish_flavor
        List<DishFlavor> dishFlavor = dishDTO.getFlavors();
        if(dishFlavor != null && dishFlavor.size() > 0){
            for (DishFlavor flavor : dishFlavor) {
                flavor.setDishId(dishId);
            }
            dishFlavorMapper.save(dishFlavor);
        }


    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult( page.getTotal(),page.getResult());
    }

    @Override
    public void delete(List<Long> ids) {
        // 1.先查询各个菜品的状况，在起售的菜品，不允许删除
        for(Long id:ids){
            Dish dish = dishMapper.getDishById(id);

            if(dish.getStatus()== StatusConstant.ENABLE)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        // 2.关联了套餐的产品不让删除
        List<Long> setmealIds = setmealDishMapper.getSetmealDishByIds(ids);
        if (setmealIds!=null&&setmealIds.size() >0)
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        // 3.批量删除菜品及其菜品口味
        for(Long id:ids)
        {
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }





    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void status(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dish.setUpdateUser(BaseContext.getCurrentId());

        dishMapper.status(dish);


    }

    @Override
    public DishVO getById(Long id) {
        // 1.根据id查询菜品
        Dish dish = dishMapper.getDishById(id);

        //2. 根据id查询菜品口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.getDishFlavorsById(id);

        DishVO dishVo = new DishVO();
        BeanUtils.copyProperties(dish,dishVo);
        dishVo.setFlavors(dishFlavors);

        return dishVo;

        }

    @Override
    public void change(DishDTO dishDTO) {

        // 1.修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.status(dish);


        // 2.修改菜品口味——先删除，再新增（不能直接更新）
        dishFlavorMapper.deleteByDishId(dish.getId());



        if (dishDTO.getFlavors()!=null && !dishDTO.getFlavors().isEmpty()){
            List<DishFlavor> dishFlavors = dishDTO.getFlavors();
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());

            });
            dishFlavorMapper.save(dishFlavors);

        }

    }



    /**
     * 根据菜品分类id 查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId, String name) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .name(name)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorsById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
